﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;
using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Dapper;
using API_Service.DBHelper;

namespace API_Service.BizLogic.Admin
{
    public class AdminService: BaseLogicService
    {
        public AdminService() { }

        #region 用户服务

        public ExecutionResult<dynamic> GetUserList()
        {
            var result = new ExecutionResult<dynamic>();

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    string sql = "select * from c_emp_desc_t";

                    result.Datas = conn.Query<dynamic>(sql).ToArray();

                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult<dynamic> GetUser(string uid)
        {
            var result = new ExecutionResult<dynamic>();

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    string sql = "select * from c_emp_desc_t where userid=@uid";

                    result.Datas = conn.Query<dynamic>(sql, new
                    {
                        uid = uid

                    }).ToArray();

                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult AddUser(string viewModel)
        {
            var result = new ExecutionResult();

            dynamic vm = JsonConvert.DeserializeObject<dynamic>(viewModel);

            IDbTransaction dbTransaction = null;

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    dbTransaction = conn.BeginTransaction();

                    int i = this.GetUser((string)vm.userid).Datas.Length;

                    if (i > 0)
                    {
                        result.Status = false;
                        result.Message = vm.vcode + " : 已经存在此用户信息, 请确认.";
                    }
                    else
                    {
                        string sql = " insert into c_emp_desc_t " +
                                     " values(@userid,@username,@password,@department,@loginstatus,@cby,@cdate,@mby,@mdate) ";

                        string sql_role = " insert into c_emp_role_t " +
                                          " values(@userid,@roleid,@rolename,@cby,@cdate) ";

                        result.ExecuteCount = conn.Execute(sql, new
                        {
                            userid = (string)vm.userid,
                            username = (string)vm.username,
                            password = (string)vm.userid,
                            department = (string)vm.userdep,
                            loginstatus = "",
                            cby = (string)vm.cby,           
                            cdate = DateTime.Now,
                            mby = (string)vm.mby,       
                            mdate = DateTime.Now
                        }, dbTransaction);

                        if (result.ExecuteCount > 0)
                        {
                            foreach (var str in ((string)vm.userroles).Split('/'))
                            {
                                result.ExecuteCount = conn.Execute(sql_role, new
                                {
                                    userid = (string)vm.userid,
                                    roleid = str.Split(',')[0],
                                    rolename = str.Split(',')[1],
                                    cby = (string)vm.cby,
                                    cdate = DateTime.Now
                                }, dbTransaction);
                            }

                            if (result.ExecuteCount > 0)
                            {
                                result.Status = true;
                                result.Message = "用户添加成功.";

                                dbTransaction.Commit();
                            }
                            else
                            {
                                result.Status = false;
                                result.Message = "用户添加失败.";
                                dbTransaction.Rollback();
                            }

                        }
                        else
                        {
                            result.Status = false;
                            result.Message = "用户添加失败.";
                            dbTransaction.Rollback();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                    dbTransaction.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult DeleteUser(string uid)
        {
            var result = new ExecutionResult();

            IDbTransaction dbTransaction = null;

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    dbTransaction = conn.BeginTransaction();

                    string sql = " delete c_emp_desc_t where userid = @userid ";

                    string sql_role = " delete c_emp_role_t where userid = @userid ";

                    result.ExecuteCount = conn.Execute(sql, new
                    {
                        userid = uid
                    }, dbTransaction);

                    result.ExecuteCount = conn.Execute(sql_role, new
                    {
                        userid = uid
                    }, dbTransaction);

                    result.Status = true;
                    result.Message = "用户删除成功.";

                    dbTransaction.Commit();
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;

                    dbTransaction.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult UpdateUser(string viewModel)
        {
            var result = new ExecutionResult();

            dynamic vm = JsonConvert.DeserializeObject<dynamic>(viewModel);

            IDbTransaction dbTransaction = null;

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    dbTransaction = conn.BeginTransaction();

                    string sql = " update c_emp_desc_t set username=@username,department=@department," +
                                 " modify_by=@mby,modify_date=@mdate " +
                                 " where userid = @userid ";

                    string sql_deleterole = " delete c_emp_role_t where userid=@userid ";

                    string sql_role = " insert into c_emp_role_t " +
                                         " values(@userid,@roleid,@rolename,@cby,@cdate) ";

                    result.ExecuteCount = conn.Execute(sql, new
                    {
                        userid = (string)vm.userid,
                        username = (string)vm.username,
                        department = (string)vm.userdep,
                        loginstatus = "",
                        cby = (string)vm.cby,             
                        cdate = DateTime.Now,
                        mby = (string)vm.mby,        
                        mdate = DateTime.Now
                    }, dbTransaction);


                    result.ExecuteCount = conn.Execute(sql_deleterole, new
                    {
                        userid = (string)vm.userid,

                    }, dbTransaction);

                    foreach (var str in ((string)vm.userroles).Split('/'))
                    {
                        result.ExecuteCount = conn.Execute(sql_role, new
                        {
                            userid = (string)vm.userid,
                            roleid = str.Split(',')[0],
                            rolename = str.Split(',')[1],
                            cby = (string)vm.cby,
                            cdate = DateTime.Now
                        }, dbTransaction);
                    }

                    result.Status = true;
                    result.Message = "用户更新成功.";

                    dbTransaction.Commit();
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                    dbTransaction.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult<dynamic> GetUserRoleByID(string userid)
        {
            var result = new ExecutionResult<dynamic>();

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    string sql = "select b.* from c_emp_desc_t a, c_emp_role_t b where a.userid = b.userid and a.userid =@uid ";

                    result.Datas = conn.Query<dynamic>(sql, new
                    {
                        uid = userid

                    }).ToArray();

                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }

        #endregion

        #region 角色服务

        public ExecutionResult<dynamic> GetRoleList()
        {
            var result = new ExecutionResult<dynamic>();

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    string sql = " select * from c_role_desc_t ";

                    result.Datas = conn.Query<dynamic>(sql).ToArray();

                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult<dynamic> GetRole(string rid)
        {
            var result = new ExecutionResult<dynamic>();

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    string sql = " select * from c_role_desc_t where role_id=@rid ";

                    result.Datas = conn.Query<dynamic>(sql, new
                    {
                        rid = rid

                    }).ToArray();

                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult<dynamic> GetRoleMenu(string rid)
        {
            var result = new ExecutionResult<dynamic>();

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    string sql = " select * from c_role_menu_t where role_id=@rid ";

                    result.Datas = conn.Query<dynamic>(sql, new
                    {
                        rid = rid

                    }).ToArray();

                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult AddRole(string viewModel)
        {
            var result = new ExecutionResult();

            dynamic vm = JsonConvert.DeserializeObject<dynamic>(viewModel);

            IDbTransaction dbTransaction = null;

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    dbTransaction = conn.BeginTransaction();

                    int i = this.GetRole((string)vm.rid).Datas.Length;

                    if (i > 0)
                    {
                        result.Status = false;
                        result.Message = vm.vcode + " : 已经存在此角色信息, 请确认.";
                    }
                    else
                    {

                        string sql = "insert into c_role_desc_t " +
                                     "values(@rid,@rname,@rdesc,@cby,@cdate,@mby,@mdate)";

                        string sql_menus = "insert into c_role_menu_t " +
                                           "values(@rid,@rname,@menuid,@menuname,@menutype,@cby,@cdate,@mby,@mdate)";

                        result.ExecuteCount = conn.Execute(sql, new
                        {
                            rid = (string)vm.rid,
                            rname = (string)vm.rname,
                            rdesc = (string)vm.rdesc,
                            cby = (string)vm.cby,               //"Simon",
                            cdate = DateTime.Now,
                            mby = (string)vm.mby,               //"Simon",
                            mdate = DateTime.Now
                        }, dbTransaction);

                        foreach (var v in vm.rmenus)
                        {
                            result.ExecuteCount = conn.Execute(sql_menus, new
                            {
                                rid = (string)vm.rid,
                                rname = (string)vm.rname,
                                menuid = ((string)v).Split('^')[0],
                                menuname = ((string)v).Split('^')[1],
                                menutype = "N",
                                cby = (string)vm.cby,               //"Simon",
                                cdate = DateTime.Now,
                                mby = (string)vm.mby,               //"Simon",
                                mdate = DateTime.Now
                            }, dbTransaction);
                        }

                        result.Status = true;
                        result.Message = "角色添加成功.";

                        dbTransaction.Commit();
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;

                    dbTransaction.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult DeleteRole(string rid)
        {
            var result = new ExecutionResult();

            IDbTransaction dbTransaction = null;

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    dbTransaction = conn.BeginTransaction();

                    string sql = " delete c_role_desc_t where role_id = @rid ";

                    string sql_delete_rolemenu = "delete c_role_menu_t where role_id=@rid ";

                    result.ExecuteCount = conn.Execute(sql, new
                    {
                        rid = rid
                    }, dbTransaction);

                    result.ExecuteCount = conn.Execute(sql_delete_rolemenu, new
                    {
                        rid = rid
                    }, dbTransaction);

                    result.Status = true;
                    result.Message = "角色删除成功.";

                    dbTransaction.Commit();
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                    dbTransaction.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult UpdateRole(string viewModel)
        {
            var result = new ExecutionResult();

            dynamic vm = JsonConvert.DeserializeObject<dynamic>(viewModel);

            IDbTransaction dbTransaction = null;

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    dbTransaction = conn.BeginTransaction();

                    string sql = " update c_role_desc_t set role_name=@rname,role_desc=@rdesc, " +
                                 " modify_by=@mby,modify_date=@mdate " +
                                 " where role_id = @rid ";

                    string sql_delete_rolemenu = "delete c_role_menu_t where role_id=@rid ";

                    string sql_menus = "insert into c_role_menu_t " +
                                           "values(@rid,@rname,@menuid,@menuname,@menutype,@cby,@cdate,@mby,@mdate)";

                    result.ExecuteCount = conn.Execute(sql, new
                    {
                        rid = (string)vm.rid,
                        rname = (string)vm.rname,
                        rdesc = (string)vm.rdesc,
                        mby = (string)vm.mby,
                        mdate = DateTime.Now
                    }, dbTransaction);

                    //清空角色权限
                    result.ExecuteCount = conn.Execute(sql_delete_rolemenu, new
                    {
                        rid = (string)vm.rid
                    }, dbTransaction);

                    foreach (var v in vm.rmenus)
                    {
                        result.ExecuteCount = conn.Execute(sql_menus, new
                        {
                            rid = (string)vm.rid,
                            rname = (string)vm.rname,
                            menuid = ((string)v).Split('^')[0],
                            menuname = ((string)v).Split('^')[1],
                            menutype = "N",
                            cby = (string)vm.cby,               //"Simon",
                            cdate = DateTime.Now,
                            mby = (string)vm.mby,               //"Simon",
                            mdate = DateTime.Now
                        }, dbTransaction);
                    }


                    result.Status = true;
                    result.Message = "角色更新成功.";

                    dbTransaction.Commit();
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                    dbTransaction.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }

        #endregion

        #region 菜单服务

        public ExecutionResult<dynamic> GetMenuList()
        {
            var result = new ExecutionResult<dynamic>();

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    string sql = " select * from c_menu_desc_t order by cast(parent_id as numeric), menu_seq ";

                    result.Datas = conn.Query<dynamic>(sql).ToArray();

                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult<dynamic> GetMenu(string menuid)
        {
            var result = new ExecutionResult<dynamic>();

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    string sql = " select * from c_menu_desc_t where menu_id=@menuid ";

                    result.Datas = conn.Query<dynamic>(sql, new
                    {
                        menuid = menuid

                    }).ToArray();

                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult SaveMenu(string viewModel)
        {
            var result = new ExecutionResult();

            dynamic vms = JsonConvert.DeserializeObject<dynamic>(viewModel);

            IDbTransaction dbTransaction = null;

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    dbTransaction = conn.BeginTransaction();

                    foreach (var vm in vms)
                    {
                        string sql_select = " select * from c_menu_desc_t where menu_id=@menuid ";

                        int i = conn.Query<dynamic>(sql_select, new
                        {
                            menuid = (string)vm.menuid
                        }, dbTransaction).ToArray().Length;

                        if (i > 0)
                        {

                            string sql = "update c_menu_desc_t set menu_name=@menuname,menu_desc=@menudesc," +
                                          "resource_path=@resourcepath,image_url=@imageurl,resource_type=@resourcetype,menu_seq=@menuseq  " +
                                         " where menu_id = @menuid";

                            result.ExecuteCount = conn.Execute(sql, new
                            {
                                menuid = (string)vm.menuid,
                                menuname = (string)vm.menuname,
                                menudesc = (string)vm.menudesc,
                                parentid = (string)vm.parentid,
                                resourcepath = (string)vm.resourcepath,
                                imageurl = (string)vm.imageurl,
                                resourcetype = (string)vm.resourcetype,
                                menuseq = (int)vm.menuseq,
                                cby = (string)vm.cby,
                                cdate = DateTime.Now,
                                mby = (string)vm.mby,
                                mdate = DateTime.Now
                            }, dbTransaction);
                        }
                        else
                        {

                            string sql = "insert into c_menu_desc_t " +
                                         "values(@menuid,@menuname,@menudesc," +
                                         " @parentid,@resourcepath,@imageurl, @resourcetype, @menuseq ,@cby,@cdate,@mby,@mdate)";

                            result.ExecuteCount = conn.Execute(sql, new
                            {
                                menuid = (string)vm.menuid,
                                menuname = (string)vm.menuname,
                                menudesc = (string)vm.menudesc,
                                parentid = (string)vm.parentid,
                                resourcepath = (string)vm.resourcepath,
                                imageurl = (string)vm.imageurl,
                                resourcetype = (string)vm.resourcetype,
                                menuseq = (int)vm.menuseq,
                                cby = (string)vm.cby,
                                cdate = DateTime.Now,
                                mby = (string)vm.mby,
                                mdate = DateTime.Now
                            }, dbTransaction);

                            result.Status = true;
                            result.Message = "菜单保存成功.";
                        }
                    }

                    dbTransaction.Commit();
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;

                    dbTransaction.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
        public ExecutionResult DeleteMenu(string menuid)
        {
            var result = new ExecutionResult();

            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    conn.Open();

                    string sql = " delete c_menu_desc_t where menu_id = @menuid ";

                    result.ExecuteCount = conn.Execute(sql, new
                    {
                        menuid = menuid
                    });

                    result.Status = true;
                    result.Message = "菜单删除成功.";
                }
                catch (Exception ex)
                {
                    Logger.WriteError(MethodBase.GetCurrentMethod(), ex);
                    result.Status = false;
                    result.Message = "Error: " + ex.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }

        #endregion

    }
}